package com.dooboolab.fluttersound;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;


public class FlutterSoundManager {
    public MethodChannel channel;
    public List<FlutterSoundSession> slots;

    void init(MethodChannel aChannel) {
        if (slots == null) {
            slots = new ArrayList<FlutterSoundSession>();
        }
        channel = aChannel;
    }


    void invokeMethod(String methodName, Map dic) {
        channel.invokeMethod(methodName, dic);
    }

    void freeSlot(int slotNo) {
        slots.set(slotNo, null);
    }


    public FlutterSoundSession getSession(final MethodCall call) {
        int slotNo = call.argument("slotNo");
        if ((slotNo < 0) || (slotNo > slots.size()))
            throw new RuntimeException();

        if (slotNo == slots.size()) {
            slots.add(slotNo, null);
        }

        return slots.get(slotNo);
    }

    public void initSession(final MethodCall call, FlutterSoundSession aPlayer) {
        int slot = call.argument("slotNo");
        slots.set(slot, aPlayer);
        aPlayer.init(slot);
    }

    public void resetPlugin(final MethodCall call, final Result result) {
        for (int i = 0; i < slots.size(); ++i) {
            if (slots.get(i) != null) {
                slots.get(i).reset(call, result);
            }
            slots = new ArrayList<FlutterSoundSession>();
        }
        result.success(0);
    }

}
